import os
import typing
import logging
import ipywidgets as widgets
from src.mod import Interface
import src.utils.dirs as dirs
import src.utils as utils


logger = logging.getLogger()


class ModelInterface(Interface):
    name: typing.ClassVar[str] = "Модели"

    def __init__(self, config, params) -> None:
        super().__init__(config, params)

        self.label_key = widgets.HTML(
            value='Нейросеть для обучения: ',
            layout={'width': 'auto', 'grid_area': 'label_key'})
        self.label_value = widgets.HTML(
            value='Не выбрана', layout={
                'width': 'auto', 'grid_area': 'label_value'})

        self.btn_add_model = widgets.Button(
            description='Создать',
            layout={'width': 'auto', 'grid_area': 'btn_add_model'})
        self.btn_add_model.on_click(self.add_model)

        self.new_model_input = widgets.Text(
            placeholder='Введите имя новой модели',
            disabled=False,
            layout={'width': 'auto', 'grid_area': 'new_model_input'}
        )
        self.children = [
            self.label_key,
            self.label_value,
            self.new_model_input,
            self.btn_add_model,
            self.generate_models()
        ]
        self.box = widgets.GridBox(
            children=self.children,
            layout={
                'grid_template_rows': 'auto auto auto',
                # 'grid_template_columns': '25% 25%',
                'grid_template_areas': '''
                "label_key label_value"
                "new_model_input btn_add_model"
                "change_model change_model"
                '''
            })

    def add_model(self, call):
        if new_model_name := self.new_model_input.value:
            if new_model_path := dirs.create_model_dir(
                os.path.join(
                    self.config["models_dir"], new_model_name)
            ):
                logger.debug(f"Create new_model: {new_model_name}")
                logger.debug(f"Path new_model: {new_model_path}")
                self.change_children(
                    self.vbox_models,
                    self.new_model(new_model_name),
                    list.append)
                self.update_display(self.box)
            else:
                logger.info(
                    f"Нейросеть с таким именем ({new_model_name}) уже существует!")
            self.new_model_input.value = ""

    def new_model(self, model: str, change: bool = False):
        logger.debug(f"Create widgets: {model} | change: {change}")
        select_button = widgets.Button(
            layout={'width': '60px'}, icon='check')
        select_button.style.button_color = '#163D6C' if change else 'green'
        select_button.on_click(
            lambda call, model_name=model: self.select_model(model_name))
        delete_button = widgets.Button(
            layout={'width': '60px'}, icon='trash')
        delete_button.style.button_color = '#E22C38'
        delete_button.on_click(
            lambda call, model_name=model: self.delete_model(model_name))
        return widgets.HBox(
            [
                widgets.Text(value=model, disabled=True),
                select_button,
                delete_button
            ])

    def generate_models(self):
        model_rows = []
        for model in utils.yield_iterable(dirs.get_model_folders(
            self.config["models_dir"]
        )):
            model_rows.append(self.new_model(model))
        self.vbox_models = widgets.VBox(
            model_rows, layout={'width': 'auto', 'grid_area': 'change_model'})
        return self.vbox_models

    def select_model(self, model_name: str):
        if self.label_value.value != model_name:
            _1break, _2break = False, False
            for widget in self.vbox_models.children:
                if widget.children[0].value == model_name:
                    widget.children[1].style.button_color = '#163D6C'
                    _1break = True
                if widget.children[0].value == self.label_value.value:
                    widget.children[1].style.button_color = 'green'
                    _2break = True
                if _1break and _2break:
                    break
            logger.debug(f"Choice model: {model_name}")
            self.label_value.value = model_name
            self.params.model_path = os.path.join(
                self.config["models_dir"], model_name)

    def delete_model(self, model_name: str):
        if dirs.remove_dir(
                os.path.join(self.config["models_dir"], model_name)):
            logger.debug(f"Delete: {model_name}")
            for index, widget in enumerate(self.vbox_models.children, 0):
                if widget.children[0].value == model_name:
                    break
            self.change_children(
                self.vbox_models, index, list.pop)
            logger.debug(f"Delete widgets: vbox_models index: {index}")
        else:
            logger.debug(f"NOT Delete {model_name} check code and log")
